<template>
  <el-config-provider>
    <router-view />
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, provide, onMounted, watch } from 'vue';
import '@/assets/styles/theme.scss';
import { useUserStore } from '@/stores/user';

// 获取用户状态管理
const userStore = useUserStore();

// 主题状态管理
const isDark = ref(false);

// 切换深色/浅色模式
const toggleDarkMode = () => {
  isDark.value = !isDark.value;
  applyTheme();
  
  // 存储主题偏好
  localStorage.setItem('theme', isDark.value ? 'dark' : 'light');
};

// 应用主题到DOM
const applyTheme = () => {
  if (isDark.value) {
    document.documentElement.classList.add('dark-theme');
  } else {
    document.documentElement.classList.remove('dark-theme');
  }
};

// 初始化时检查用户之前的主题偏好和用户状态
onMounted(async () => {
  // 检查系统偏好
  const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
  
  // 优先使用保存的偏好，如果没有则使用系统偏好
  const savedTheme = localStorage.getItem('theme');
  if (savedTheme === 'dark' || (savedTheme === null && prefersDark)) {
    isDark.value = true;
  }
  
  // 应用主题
  applyTheme();
  
  // 监听系统主题变化
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
    if (localStorage.getItem('theme') === null) {
      isDark.value = e.matches;
      applyTheme();
    }
  });
  
  // 初始化用户状态
  if (userStore.token) {
    try {
      await userStore.fetchUserInfo();
    } catch (error) {
      console.error('获取用户信息失败:', error);
    }
  }
});

// 提供主题切换功能给子组件
provide('isDark', isDark);
provide('toggleDarkMode', toggleDarkMode);
</script>

<style>
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  background-color: var(--bg-color);
  color: var(--text-color);
  transition: background-color 0.3s, color 0.3s;
}

#app {
  height: 100%;
  width: 100%;
  background-color: var(--bg-color);
  transition: background-color 0.3s;
}
</style> 